package com.yituo.mjworld.mvc.action.user;

import com.yituo.mjworld.core.annotation.Auth;
import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.annotation.Rule;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.action.IBaseAction;
import com.yituo.mjworld.mvc.entity.web.WebUser;
import com.yituo.mjworld.mvc.entity.web.WebUserAddress;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.service.impl.UserAddressServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 用户地址模块
 *
 * @author Administrator
 */
@Component
public class UserAddressAction implements IBaseAction {
  @Autowired
  UserAddressServiceImpl userAddressService;

  /**
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(admin_user = true)
  @Check(form = QueryForm.class)
  public void getList(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebUser user = req.getCurrentUser();
    QueryForm form = (QueryForm) req.getForm();
    form.getParam().clear();
    form.getParam().put("userId", user.getId());
    res.success(userAddressService.getList(form));
  }

  /**
   * 删除一个收货地址
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(admin_user = true)
  @Check(form = DeleteForm.class)
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebUser user = req.getCurrentUser();
    DeleteForm form = (DeleteForm) req.getForm();
    form.getParam().clear();
    form.getParam().put("userId", user.getId());
    form.getParam().put("id", form.getId());
    res.setResult(userAddressService.delete(form));
  }

  /**
   * 新增或者修改一个收获地址
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Auth(admin_user = true)
  @Check(form = WebUserAddress.class)
  public void saveOrUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException {
    WebUserAddress form = (WebUserAddress) req.getForm();
    res.setResult(userAddressService.saveOrUpdate((WebUserAddress) req.getForm()));
  }

  /**
   * 设置默认地址
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Auth(admin_user = true)
  @Rule(name_zn = "默认地址ID", name = "id", min = "0")
  public void setDefault(MyHttpRequest req, MyHttpResponse res) throws IOException {
    int addId = Integer.parseInt(req.getParameter("id"));
    res.setResult(userAddressService.setDefault(req.getCurrentUser().getId(), addId));
  }

  /**
   * 获取用户默认的收获地址
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Auth(admin_user = true)
  public void getDefault(MyHttpRequest req, MyHttpResponse res) throws IOException {
    res.success(userAddressService.getUserAddress(req.getCurrentUser().getId()));
  }
}
